package Control;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingWorker;

import Entity.Shop_Catalog;
import Entity.Shop_Product;
import Entity.Workshop_WorkshopCategory;
import Form.Main;
import Form.Shop_Product_Administrate_Form;

public class Shop_Product_Administrate_Controller {
	
	private Shop_Product_Administrate_Form parser;
	private String frontImageUrl, backImageUrl;
	private BufferedImage frontImage, backImage;
	private String updatefrontImageUrl, updatebackImageUrl;
	private BufferedImage updatefrontImage, updatebackImage;
	private ArrayList<Shop_Catalog> catalogList;
	private Shop_Catalog selectedCatalog;
	private Shop_Catalog updateSelectedCatalog;
	private ArrayList <Shop_Product> productList;
	private Shop_Product selectedProduct;
	private String selectedWorkshop;
	private ArrayList<Workshop_WorkshopCategory> categoryList;
	private ArrayList<String> categoryIdList;
	
	public Shop_Product_Administrate_Controller(Shop_Product_Administrate_Form parser){
		setParser(parser);
	}
	
	public void getProducts(final int catalog){
		SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>(){

			@Override
			protected Void doInBackground() throws Exception {
				if(catalog == 0){
					productList = Shop_Product.getProducts();
				}
				else{
					productList = Shop_Product.getProductsUnderCat(catalogList.get(catalog - 1).getId());
				}
				return null;
			}
			
			protected void done(){
				SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>(){

					@Override
					protected Void doInBackground() throws Exception {
						setSkill();
						return null;
					}
					
					protected void done(){
						parser.getParser().closeProgressBar();
						parser.getProductsList().removeAll();
						parser.getProductsList().repaint();
						final JPanel products = parser.getProductsList();
						reset();
						for(int i = 0; i < productList.size(); i++){
							final int index = i;
							
							final JLabel product = new JLabel();
							product.setBorder(BorderFactory.createLineBorder(Color.GRAY, 3));
							product.setPreferredSize(new Dimension(50, 50));
							product.setHorizontalAlignment(JLabel.CENTER);
							product.setIcon(new ImageIcon(Toolkit.getDefaultToolkit().createImage(productList.get(i).getFrontImageUrl()).getScaledInstance(40, 40, Image.SCALE_DEFAULT)));
							product.addMouseListener(new MouseListener(){
			
								@Override
								public void mouseClicked(MouseEvent arg0) {
									selectedProduct = productList.get(index);
									getParser().getUpdate().setVisible(true);
									resetDefault();
								}
			
								@Override
								public void mouseEntered(MouseEvent arg0) {
									product.setIcon(new ImageIcon(Toolkit.getDefaultToolkit().createImage(productList.get(index).getBackImageUrl()).getScaledInstance(40, 40, Image.SCALE_DEFAULT)));
									product.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 3));
								}
			
								@Override
								public void mouseExited(MouseEvent arg0) {
									product.setIcon(new ImageIcon(Toolkit.getDefaultToolkit().createImage(productList.get(index).getFrontImageUrl()).getScaledInstance(40, 40, Image.SCALE_DEFAULT)));
									product.setBorder(BorderFactory.createLineBorder(Color.GRAY, 3));
								}
			
								@Override
								public void mousePressed(MouseEvent arg0) {
									// TODO Auto-generated method stub
									
								}
			
								@Override
								public void mouseReleased(MouseEvent arg0) {
									// TODO Auto-generated method stub
									
								}
								
							});
							products.add(product);
						}
						
						parser.getParser().closeProgressBar();
					}
					
				};
				parser.getParser().getProgressBar();
				worker.execute();
			}
			
		};
		parser.getParser().getProgressBar();
		worker.execute();
		
		
	}
	
	public boolean selectSkill(){
		boolean chose = false;
		
		ArrayList<Workshop_WorkshopCategory> workshopCategories = new ArrayList<Workshop_WorkshopCategory>();
		workshopCategories = Workshop_WorkshopCategory.retrieveAllCategory();
		ArrayList<String> workshopCategoriesNames = new ArrayList<String>();
		String[] workshopCategoriesDesc = new String[workshopCategories.size()+1];
		workshopCategoriesDesc[0] = "None";
		for(int i = 1; i < workshopCategories.size()+1; i++){
			workshopCategoriesDesc[i] = workshopCategories.get(i-1).getDescription();
			workshopCategoriesNames.add(workshopCategories.get(i-1).getDescription());
		}
		String response = (String)JOptionPane.showInputDialog(parser.getParser(), "Select skill required for making the product:", "Select Skill", JOptionPane.PLAIN_MESSAGE, null, workshopCategoriesDesc, "None");
		if(response != null && response.length() > 0){
			chose = true;
			int index = workshopCategoriesNames.indexOf(response);
			if(index == -1){
				selectedWorkshop = "None";
			}
			else{
				selectedWorkshop = workshopCategories.get(index).getCategoryCode();
			}
		}
		
		return chose;
	}
	
	public void saveProduct(){
		boolean hasImage = true;
		if(frontImageUrl == null || backImageUrl == null)
			hasImage = false;
		if(CommonControls.validatePanelFields(parser.getCreate()) && hasImage){
			boolean selected = selectSkill();
			if(selected){
				boolean success = false;
				Shop_Product product = new Shop_Product(parser.getLblIdentificationNumber().getText());
				
				try {
					ImageIO.write(frontImage, "png", new File("Resources/Images/Default/"+product.getProductId()+"_front.png"));
					ImageIO.write(backImage, "png", new File("Resources/Images/Default/"+product.getProductId()+"_back.png"));
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				if(parser.getChckbxNewcatalog().isSelected()){
					Shop_Catalog catalog = new Shop_Catalog(CommonControls.generateDefaultType5DigitCode('C'), parser.getTxtCategoryname().getText(), parser.getTxtrCategorydesc().getText(), CommonControls.getCurrentDate(), null, "AVA");
					success = catalog.createCatalog();
					
					if(!success){
						parser.getParser().displayMessage(success, "Error encountered while creating new catalog record.");
						return;
					}
					
					product.setCatalog(catalog);
				}
				else{
					product.setCatalog(catalogList.get(parser.getComboBox().getSelectedIndex() - 1));
				}
				
				product.setName(parser.getTxtName().getText());
				product.setDescription(parser.getDescription().getText());
				product.setFrontImageUrl("Resources/Images/Default/"+product.getProductId()+"_front.png");
				product.setBackImageUrl("Resources/Images/Default/"+product.getProductId()+"_back.png");
				product.setCreateDate(CommonControls.getCurrentDate());
				product.setUnitPrice((Double)parser.getPrice().getValue());
				product.setWorkshopId(selectedWorkshop);
				
				success = product.createProduct();
				
				if(!success){
					parser.getParser().displayMessage(success, "Error encountered while creating new product record.");
					return;
				}
				else{
					parser.getParser().displayMessage(success, "Successfully created new product record.");
					setCatalogs();
					parser.getCreateDialog().setVisible(false);
					reset();
					return;
				}
			}
		}
		else{
			if(!hasImage)
				Main.frame.displayMessage(false, "Please upload images for both the front and back of product.");
		}
	}
	
	public void updateProduct(){
		boolean hasImage = true;
		if(CommonControls.validatePanelFields(parser.getUpdate()) && hasImage){
			boolean success = false;
			if(parser.getStatusComboBox().getSelectedIndex() == 0)
				selectedProduct.getProductStatus().setStatusCode("AVA");
			else
				selectedProduct.getProductStatus().setStatusCode("UVA");
			selectedProduct.setName(parser.getTxtTextname().getText());
			selectedProduct.setDescription(parser.getTxtrTxtdescription().getText());
			try {
				if(updatefrontImage != null && updatebackImage != null){
					ImageIO.write(updatefrontImage, "png", new File("Resources/Images/Default/"+selectedProduct.getProductId()+"_front.png"));
					ImageIO.write(updatebackImage, "png", new File("Resources/Images/Default/"+selectedProduct.getProductId()+"_back.png"));
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			selectedProduct.setUnitPrice((Double)parser.getPrice_1().getValue());
			if(parser.getChckbxNewCatalog_1().isSelected()){
				Shop_Catalog catalog = new Shop_Catalog(CommonControls.generateDefaultType5DigitCode('C'), parser.getTxtCatname().getText(), parser.getTxtrCatdesc().getText(), CommonControls.getCurrentDate(), null, "AVA");
				success = catalog.createCatalog();
					
				if(!success){
					parser.getParser().closeProgressBar();
					parser.getParser().displayMessage(success, "Error encountered while creating new catalog record.");
					return;
				}
				
				selectedProduct.setCatalog(catalog);
			}
			else{
				selectedProduct.setCatalog(catalogList.get(parser.getComboBox_1().getSelectedIndex()));
			}
			selectedProduct.setWorkshopId(categoryList.get(parser.getComboBoxSkill().getSelectedIndex()-1).getCategoryCode());
			success = selectedProduct.updateProduct();
			if(!success){
				parser.getParser().closeProgressBar();
				parser.getParser().displayMessage(success, "Error encountered while updating product record.");
				return;
			}
			else{
				parser.getParser().closeProgressBar();
				parser.getParser().displayMessage(success, "Successfully updated product record.");
				setCatalogs();
				return;
			}
		}
		else{
			if(!hasImage)
				Main.frame.displayMessage(false, "Please upload images for both the front and back of product.");
		}
	}
	
	public void generateProductId(){
		parser.getLblIdentificationNumber().setText(CommonControls.generateDefaultType5DigitCode('P'));
	}
	
	public void setCatalogs(){
		parser.getCatalogs().setModel(new DefaultComboBoxModel(new String[] {"All"}));
		parser.getComboBox().setModel(new DefaultComboBoxModel(new String[] {"Select a catalog..."}));
		parser.getComboBox_1().setModel(new DefaultComboBoxModel(new String[] {}));
		SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>(){

			@Override
			protected Void doInBackground() throws Exception {
				catalogList = Shop_Catalog.retrieveAllCatalogs();
				return null;
			}
			
			protected void done(){
				for(int i = 0; i < catalogList.size(); i++){
					parser.getComboBox().addItem(catalogList.get(i).getName());
					parser.getCatalogs().addItem(catalogList.get(i).getName());
					parser.getComboBox_1().addItem(catalogList.get(i).getName());
				}
				getProducts(parser.getCatalogs().getSelectedIndex());
				changeUpdateCatalogDetails();
				if(selectedProduct != null)
					resetDefault();
				parser.getParser().closeProgressBar();
			}
		};
		parser.getParser().getProgressBar();
		worker.execute();
	}
	
	public void setSkill(){
		categoryList = Workshop_WorkshopCategory.retrieveAllCategory();
		categoryIdList = new ArrayList<String>();
		getParser().getComboBoxSkill().removeAllItems();
		getParser().getComboBoxSkill().addItem("None");
		for(int i = 0; i < categoryList.size(); i++){
			getParser().getComboBoxSkill().addItem(categoryList.get(i).getDescription());
			categoryIdList.add(categoryList.get(i).getCategoryCode());
		}
		if(!selectedProduct.getWorkshopId().equals("None")){
			int index = categoryIdList.indexOf(selectedProduct.getWorkshopId());
			parser.getComboBoxSkill().setSelectedItem(categoryList.get(index).getDescription());
		}
		else{
			parser.getComboBoxSkill().setSelectedItem("None");
		}
	}
	
	public void changeCatalogDetails(){
		setSelectedCatalog(catalogList.get(parser.getComboBox().getSelectedIndex() - 1));
		parser.getTxtCategoryname().setText(getSelectedCatalog().getName());
		parser.getTxtrCategorydesc().setText(getSelectedCatalog().getDescription());
	}
	
	public void changeUpdateCatalogDetails(){
		setUpdateSelectedCatalog(catalogList.get(parser.getComboBox_1().getSelectedIndex()));
		parser.getTxtCatname().setText(getUpdateSelectedCatalog().getName());
		parser.getTxtrCatdesc().setText(getUpdateSelectedCatalog().getDescription());
	}
	
	public void reset(){
		frontImageUrl = null;
		backImageUrl = null;
		parser.getLblFrontimage().setIcon(new ImageIcon(Toolkit.getDefaultToolkit().createImage("Resources/Images/Default/no_image.jpg").getScaledInstance(70, 70, Image.SCALE_DEFAULT)));
		parser.getLblBackimage().setIcon(new ImageIcon(Toolkit.getDefaultToolkit().createImage("Resources/Images/Default/no_image.jpg").getScaledInstance(70, 70, Image.SCALE_DEFAULT)));
		generateProductId();
		parser.getTxtName().setText("");
		parser.getDescription().setText("");
		parser.getPrice().setValue(25);
		parser.getComboBox().setSelectedIndex(0);
		parser.getChckbxNewcatalog().setSelected(false);
		parser.getTxtCategoryname().setEnabled(false);
		parser.getTxtCategoryname().setText("");
		parser.getTxtrCategorydesc().setEnabled(false);
		parser.getTxtrCategorydesc().setText("");
	}
	
	public void resetDefault(){
		if(selectedProduct.getProductStatus().getStatusCode().equals("AVA"))
			parser.getStatusComboBox().setSelectedIndex(0);
		else
			parser.getStatusComboBox().setSelectedIndex(1);
		if(!selectedProduct.getWorkshopId().equals("None")){
			int index = categoryIdList.indexOf(selectedProduct.getWorkshopId());
			parser.getComboBoxSkill().setSelectedItem(categoryList.get(index).getDescription());
		}
		else{
			parser.getComboBoxSkill().setSelectedItem("None");
		}
		parser.getLblId_1().setText(selectedProduct.getProductId());
		parser.getTxtTextname().setText(selectedProduct.getName());
		parser.getTxtrTxtdescription().setText(selectedProduct.getDescription());
		parser.getLblFrontimage_1().setIcon(new ImageIcon(Toolkit.getDefaultToolkit().createImage(selectedProduct.getFrontImageUrl()).getScaledInstance(70, 70, Image.SCALE_DEFAULT)));
		parser.getLblBackimage_1().setIcon(new ImageIcon(Toolkit.getDefaultToolkit().createImage(selectedProduct.getBackImageUrl()).getScaledInstance(70, 70, Image.SCALE_DEFAULT)));
		parser.getPrice_1().setValue(selectedProduct.getUnitPrice());
		selectedProduct.getCatalog().getCatalogDetailsById();
		parser.getComboBox_1().setSelectedItem(selectedProduct.getCatalog().getName());
		parser.getTxtCatname().setText(selectedProduct.getCatalog().getName());
		parser.getTxtrCatdesc().setText(selectedProduct.getCatalog().getDescription());
		
		parser.getChckbxNewCatalog_1().setSelected(false);
		parser.getTxtCatname().setEditable(false);
		parser.getTxtrCatdesc().setEditable(false);
	}

	public Shop_Product_Administrate_Form getParser() {
		return parser;
	}

	public void setParser(Shop_Product_Administrate_Form parser) {
		this.parser = parser;
	}

	public String getFrontImageUrl() {
		return frontImageUrl;
	}

	public void setFrontImageUrl() {
		JFileChooser browse = new JFileChooser();
		int response = browse.showOpenDialog(parser.getParser());
		if(response == JFileChooser.APPROVE_OPTION){
			frontImageUrl = browse.getSelectedFile().getAbsolutePath();
			try {
				frontImage = ImageIO.read(new File(frontImageUrl));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			parser.getLblFrontimage().setIcon(new ImageIcon(frontImage.getScaledInstance(70, 70, Image.SCALE_DEFAULT)));
		}
	}

	public String getBackImageUrl() {
		return backImageUrl;
	}

	public void setBackImageUrl() {
		JFileChooser browse = new JFileChooser();
		int response = browse.showOpenDialog(parser.getParser());
		if(response == JFileChooser.APPROVE_OPTION){
			backImageUrl = browse.getSelectedFile().getAbsolutePath();
			try {
				backImage = ImageIO.read(new File(backImageUrl));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			getParser().getLblBackimage().setIcon(new ImageIcon(backImage.getScaledInstance(70, 70, Image.SCALE_DEFAULT)));
		}
	}
	
	public String getUpdatefrontImageUrl() {
		return updatefrontImageUrl;
	}

	public void setUpdatefrontImageUrl() {
		JFileChooser browse = new JFileChooser();
		int response = browse.showOpenDialog(parser);
		if(response == JFileChooser.APPROVE_OPTION){
			updatefrontImageUrl = browse.getSelectedFile().getAbsolutePath();
			try {
				updatefrontImage = ImageIO.read(new File(updatefrontImageUrl));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			parser.getLblFrontimage_1().setIcon(new ImageIcon(updatefrontImage.getScaledInstance(70, 70, Image.SCALE_DEFAULT)));
		}
	}

	public String getUpdatebackImageUrl() {
		return updatebackImageUrl;
	}

	public void setUpdatebackImageUrl() {
		JFileChooser browse = new JFileChooser();
		int response = browse.showOpenDialog(parser);
		if(response == JFileChooser.APPROVE_OPTION){
			updatebackImageUrl = browse.getSelectedFile().getAbsolutePath();
			try {
				updatebackImage = ImageIO.read(new File(updatebackImageUrl));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			parser.getLblBackimage_1().setIcon(new ImageIcon(updatebackImage.getScaledInstance(70, 70, Image.SCALE_DEFAULT)));
		}
	}

	public BufferedImage getUpdatefrontImage() {
		return updatefrontImage;
	}

	public void setUpdatefrontImage(BufferedImage updatefrontImage) {
		this.updatefrontImage = updatefrontImage;
	}

	public BufferedImage getUpdatebackImage() {
		return updatebackImage;
	}

	public void setUpdatebackImage(BufferedImage updatebackImage) {
		this.updatebackImage = updatebackImage;
	}

	public Shop_Catalog getSelectedCatalog(){
		return selectedCatalog;
	}

	public void setSelectedCatalog(Shop_Catalog selectedCatalog) {
		this.selectedCatalog = selectedCatalog;
	}

	public Shop_Catalog getUpdateSelectedCatalog() {
		return updateSelectedCatalog;
	}

	public void setUpdateSelectedCatalog(Shop_Catalog updateSelectedCatalog) {
		this.updateSelectedCatalog = updateSelectedCatalog;
	}

	public Shop_Product getSelectedProduct() {
		return selectedProduct;
	}

	public void setSelectedProduct(Shop_Product selectedProduct) {
		this.selectedProduct = selectedProduct;
	}

	public String getSelectedWorkshop() {
		return selectedWorkshop;
	}

	public void setSelectedWorkshop(String selectedWorkshop) {
		this.selectedWorkshop = selectedWorkshop;
	}

}
